#region Copyright

// The contents of this file are subject to the Mozilla Public License
//  Version 1.1 (the "License"); you may not use this file except in compliance
//  with the License. You may obtain a copy of the License at
//  
//  http://www.mozilla.org/MPL/
//  
//  Software distributed under the License is distributed on an "AS IS"
//  basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
//  License for the specific language governing rights and limitations under 
//  the License.
//  
//  The Initial Developer of the Original Code is Robert Smyth.
//  Portions created by Robert Smyth are Copyright (C) 2008.
//  
//  All Rights Reserved.

#endregion

using System;
using NUnitGrid.Framework;
using NUnitGrid.Framework.Env;
using NUnitGrid.Framework.Logging;


namespace NUnitGrid.Node.Runner
{
    public class ProcessWithEnvVariablesRunner : IProcessCompletedListener
    {
        private readonly string commandLine;
        private readonly IEnvironmentVariable[] environmentVariables;
        private readonly string fileName;
        private readonly IRunProgressListener listener;
        private readonly ILogger logger;
        private readonly ISchedule schedule;
        private readonly TimeSpan timeLimit;
        private readonly string workingDirectory;

        public ProcessWithEnvVariablesRunner(IRunProgressListener listener, ISchedule schedule, string workingDirectory,
                                             string fileName, string commandLine, TimeSpan timeLimit,
                                             IEnvironmentVariable[] environmentVariables, ILogger logger)
        {
            this.listener = listener;
            this.schedule = schedule;
            this.workingDirectory = workingDirectory;
            this.fileName = fileName;
            this.commandLine = commandLine;
            this.timeLimit = timeLimit;
            this.environmentVariables = environmentVariables;
            this.logger = logger;
        }

        public void Start()
        {
            logger.Verbose.Write("Starting task");

            using (
                new EnvironmentVariablesScope(new EnvironmentVariable("NUnitGridRunner.ProcessID",
                                                                      GridNodeSettings.Default.Nickname)))
            using (new EnvironmentVariablesScope(environmentVariables))
            {
                var process = new AsynchronousProcessRunner(
                    workingDirectory,
                    fileName,
                    commandLine,
                    schedule,
                    timeLimit,
                    this,
                    logger);
                process.Start();
            }
        }

        void IProcessCompletedListener.OnCompleted(int threadResultCode, string textOutput)
        {
            logger.Verbose.Write("Task completed");

            var succeeded = true;
            if (textOutput.Contains("Test Case Failures:"))
            {
                succeeded = false;
                textOutput += "\nNUnit reports test case failures in output text.\n";
            }

            if (threadResultCode > 0)
            {
                succeeded = false;
                textOutput += string.Format("\n{0} tests failed.\n", threadResultCode);
            }

            if (threadResultCode == -1)
            {
                succeeded = false;
                textOutput += string.Format("\nNUnit returned error code was {0}. General error running tests.\n",
                                            threadResultCode);
            }
            else if (threadResultCode == -2)
            {
                succeeded = false;
                textOutput +=
                    string.Format(
                        "\nNUnit returned error code was {0}. An internal NUnit error to be reported to the NUnit developers.\n",
                        threadResultCode);
            }
            else if (threadResultCode < 0)
            {
                succeeded = false;
                textOutput += string.Format("\nNUnit returned error code was {0}.\n", threadResultCode);
            }

            listener.OnCompleted(textOutput, succeeded, threadResultCode != 0);
        }
    }
}